<?php

include 'globals.php';

function get_db_conn()
{
    $conn = mysql_connect($GLOBALS['db_ip'], $GLOBALS['db_user'], $GLOBALS['db_pass']);
    mysql_select_db($GLOBALS['db_name'], $conn);
    return $conn;
}

function get_friends($user)
{
    global $facebook;
    return $facebook->api_client->friends_get();
}

function test_valid_ics($str)
{
    if($str != "" && !test_404($str . ".ics"))
        return true;
    return false;
}

function is_valid_schedule($str)
{
    if($str != "" && !test_404("http://scheduleman.org/schedules/".$str.".ics"))
        return true;
    return false;
}

function get_cal_string($user, $sem = NULL)
{
    $link = @mysql_connect($GLOBALS["db_host"], $GLOBALS["db_user"], $GLOBALS["db_pass"]);
    @mysql_select_db($GLOBALS["db_name"]);
    
    if($sem === NULL)
     $sem = $GLOBALS["semester"];
    
    $cal_res = mysql_query("SELECT cal_string from cal_strings WHERE semester='$sem' AND uid=$user");
    if(mysql_num_rows($cal_res) == 0)
    {
    		mysql_close($link);
        return "0";
    }
    else
    {
        $cal_string = '';
        while ($row = mysql_fetch_array($cal_res))
            $cal_string = stripslashes($row['cal_string']);
        return $cal_string;
    }
    mysql_close($link);
}

function get_cal_strings($friends)
{
    $friend_cals = array();
    $link = @mysql_connect($GLOBALS["db_host"], $GLOBALS["db_user"], $GLOBALS["db_pass"]);
    @mysql_select_db($GLOBALS["db_name"]);
    $friends_cals_sql_string = 'SELECT * FROM cal_strings WHERE ';
    foreach($friends as $friend)
    {
        $friends_cals_sql_string .= "uid = ".$friend." OR ";
    }
    $friends_cals_sql_string .= "uid = 0;";
    $friends_cals_sql = mysql_query($friends_cals_sql_string);
    if(mysql_num_rows($friends_cals_sql) == 0)
    {
        mysql_close($link);
        return $friend_cals;
    }
    else
    {
        while ($row = mysql_fetch_array($friends_cals_sql))
        {
            $cal_string = stripslashes($row['cal_string']);
            $friend_uid = stripslashes($row['uid']);
            $friend_cals[$friend_uid] = $cal_string;
        }
        mysql_close($link);
        return $friend_cals;
    }
}

function test_404($url)
{
    $handle = curl_init($url);
    curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    /* Get the HTML or whatever is linked in $url. */
    $response = curl_exec($handle);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
    if($httpCode == 404) {
        curl_close($handle);
        return true;
    }

    curl_close($handle);
    return false;

    /* Handle $response here. */
    
}
?>